/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/**
 * 可疑驿站地址审核
 */
import React, { useRef, useEffect, useState, useMemo } from 'react';
import { Popconfirm, message, Input, Button, Drawer, Spin, Row, Col, Divider, Space } from 'antd';
import { getTableList, operation, getYzInfo, getYzLogList } from '@/services/operatorManagement';
import ProTable from '@ant-design/pro-table';
import DragTable from '@/components/DragTable';
import RefuseModal from '@/components/RefuseModal';
import ProDescriptions from '@ant-design/pro-descriptions';
import { debounce } from 'lodash';
import { useSelector } from 'umi';
import type { ConnectState } from '@/models/connect';
import KbRefuseModal from './RefuseForm';
import { recordColumns } from '../types/SuspiciousInnCheck.d';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import type { TableListItem } from '../types/SuspiciousInnCheck';

interface CommonTableType {
  activeKey: string;
  type: string;
  show?: boolean;
}

const sensitiveChange = (str: string = '', checkWord: string = '') => {
  const sen_word = str.split(',');
  let word = checkWord;
  sen_word.forEach((val) => {
    word = word.replace(val, `<font color="red">${val}</font>`);
  });

  return <span dangerouslySetInnerHTML={{ __html: word }} />;
};

const CommonTable = ({ type, activeKey, show }: CommonTableType) => {
  const { winSize } = useSelector((state: ConnectState) => state.global);
  const actionRef = useRef<ActionType>();
  const [record, setRecord] = useState<any>({});
  const [visible, setVisible] = useState<boolean>(false);
  const [formVisible, setFormVisible] = useState<boolean>(false);
  const [submitLoading, setSubmitLoading] = useState<boolean>(false);
  const [showButton, setShowButton] = useState<boolean>(false);
  const [yzLogList, setYzLogList] = useState<any>({ page: 1, hasNextPage: true, list: [] });
  const activeKeyList = {
    check: '1',
    blackList: '2',
  };

  const handleHideMoal = () => {
    setFormVisible(false);
  };
  const options = debounce(
    ({ id, status, reject_reason_desc, reject_reason_type }: any) => {
      operation({
        id,
        status,
        reject_reason_desc,
        reject_reason_type,
      }).then((res) => {
        if (reject_reason_type) {
          setShowButton(false);
          handleHideMoal();
          getYzInfo({ id });
        }
        message.success(res.msg);
        setShowButton(false);
        actionRef.current?.reload();
      });
    },
    300,
    {
      leading: false,
      trailing: true,
    },
  );

  const getYzLog = (values: any) => {
    let { page, list } = yzLogList;
    if (values.isNext) {
      delete values.isNext;
      page = 1;
      list = [];
    }
    getYzLogList({ ...values, page, size: 10 }).then(({ code, data, msg }: any) => {
      let pages = page,
        logList = list,
        hasNext = true;
      if (code == 0) {
        if (Math.ceil(data.total / 10) > page) {
          pages += 1;
          hasNext = true;
        } else {
          hasNext = false;
        }
        logList = [...logList, ...data.list];
      } else {
        message.error(msg);
      }
      setYzLogList({ ...yzLogList, hasNextPage: hasNext, list: logList, page: pages });
    });
  };

  const handleDetail = (values: any) => {
    setSubmitLoading(true);
    if (values.page_turn) {
      values.type = activeKeyList[type];
    }
    getYzInfo(values).then((res) => {
      const { code, data, msg } = res;
      if (code == 0) {
        setVisible(true);
        setRecord(data);
        getYzLog({ cm_id: data.inn_info.cm_id, isNext: values.page_turn });
        if (type == 'check') setShowButton(true);
      } else {
        message.error(msg);
      }
      setSubmitLoading(false);
    });
  };

  const onClose = () => {
    setVisible(false);
  };

  const handleReject = (params: any) => {
    setRecord({
      inn_info: {
        id: params.id,
      },
    });
    setFormVisible(true);
  };

  const columns: ProColumns<TableListItem>[] = useMemo(() => {
    const list: ProColumns<TableListItem>[] = [
      {
        title: '',
        hideInTable: true,
        dataIndex: 'phone',
        renderFormItem: () => {
          return <Input placeholder='请输入 id/手机号/名称' />;
        },
      },
      {
        title: 'id',
        dataIndex: 'id',
        align: 'center',
        search: false,
        width: 50,
      },
      {
        title: '驿站名称',
        dataIndex: 'inn_name',
        align: 'left',
        search: false,
        render: (_, data) => {
          return sensitiveChange(data.sen_words, data.inn_name);
        },
      },
      {
        title: '驿站地址',
        dataIndex: 'inn_location',
        align: 'left',
        width: '10%',
        search: false,
        render: (_, data) => {
          return sensitiveChange(data.sen_words, data.inn_location);
        },
      },
      {
        title: '驿站账号',
        dataIndex: 'inn_phone',
        align: 'center',
        search: false,
      },
      {
        title: '联系电话',
        dataIndex: 'phone',
        align: 'center',
        search: false,
        hideInTable: type === 'blackList',
      },
      {
        title: '注册时间',
        dataIndex: 'create_time',
        align: 'center',
        search: false,
      },
      {
        title: '修改时间',
        dataIndex: 'update_time',
        align: 'center',
        search: false,
      },
      {
        title: '操作',
        width: winSize === 'xs' ? 100 : 300,
        key: 'option',
        align: 'center',
        valueType: 'option',
        fixed: 'right',
        search: false,
        render: (_, data) => (
          <Space direction={winSize === 'xs' ? 'vertical' : 'horizontal'}>
            <a onClick={handleDetail.bind(null, { id: data.id })}>查看详情</a>
            {type === 'blackList' ? (
              <Popconfirm
                title='确认取消拉黑？'
                onConfirm={() => options({ id: data.id, status: 1 })}
              >
                <a>取消拉黑</a>
              </Popconfirm>
            ) : (
              <>
                <a onClick={handleReject.bind(null, { id: data.id })}>驳回</a>
                <RefuseModal
                  tableRef={actionRef}
                  api='/Inn/updateInterceptUser'
                  label='确定扣钱不发？'
                  formData={{ id: data.id, status: 3, remark: data.inn_location }}
                >
                  <a>扣钱不发</a>
                </RefuseModal>
                <RefuseModal
                  tableRef={actionRef}
                  api='/Inn/updateInterceptUser'
                  label='确定拉黑该驿站？'
                  formData={{ id: data.id, status: 2, remark: data.inn_location }}
                >
                  <a>拉黑</a>
                </RefuseModal>
                {type !== 'pass' ? (
                  <Popconfirm
                    title='确认通过？'
                    onConfirm={() => options({ id: data.id, status: 1 })}
                  >
                    <Button type='primary' size='small' danger>
                      通过
                    </Button>
                  </Popconfirm>
                ) : null}
              </>
            )}
          </Space>
        ),
      },
    ];
    return list;
  }, [winSize]);

  const requsetTableData = (values: TableListItem) => {
    const params = type == 'blackList' ? { status: 2 } : type === 'pass' ? { status: 1 } : {};
    return getTableList({ ...params, ...values });
  };

  const handleSubmit = (values: any) => {
    const id = record.inn_info.id;
    delete values.is_approved;
    values = {
      ...values,
      status: '4',
      id,
    };
    options(values);
  };

  useEffect(() => {
    if (!show || type !== activeKey) return;
    actionRef.current?.reload();
  }, [show, type, activeKey]);

  return (
    <>
      <DragTable>
        <ProTable<TableListItem>
          actionRef={actionRef}
          rowKey='id'
          request={requsetTableData as any}
          className='kb-pro-table'
          columns={columns}
          pagination={false}
          options={false}
          search={{
            className: 'kb-pro-table-form',
            labelWidth: 'auto',
            collapseRender: () => false,
            optionRender: (_, { form }) => [
              <Button
                key='phone'
                type='primary'
                onClick={() => {
                  form?.submit();
                }}
              >
                搜索
              </Button>,
            ],
          }}
          scroll={{ x: 1300 }}
        />
      </DragTable>

      <Drawer
        visible={visible}
        width={winSize === 'xs' ? 300 : 700}
        closable={false}
        onClose={onClose}
        title='驿站详情'
      >
        <Spin spinning={submitLoading}>
          {record.inn_info ? (
            <>
              <Divider orientation='left'>驿站基础信息</Divider>
              <ProDescriptions>
                <ProDescriptions.Item span={12} label='驿站名称'>
                  {record.inn_info.inn_name}
                </ProDescriptions.Item>
                <ProDescriptions.Item span={12} label='驿站地址'>
                  {record.inn_info.full_location}
                </ProDescriptions.Item>
                <ProDescriptions.Item span={12} label='驿站账号'>
                  {record.inn_info.phone}
                </ProDescriptions.Item>
                <ProDescriptions.Item span={12} label='联系电话'>
                  {record.inn_info.concat_phone}
                </ProDescriptions.Item>
                <ProDescriptions.Item span={12} label='注册时间' valueType='dateTime'>
                  {record.inn_info.register_time}
                </ProDescriptions.Item>
                <ProDescriptions.Item span={12} label='申请时间' valueType='dateTime'>
                  {record.inn_info.apply_time}
                </ProDescriptions.Item>
                <ProDescriptions.Item span={12} label='实名认证'>
                  {record.inn_info.is_auth_realname == 1
                    ? '已实名'
                    : record.inn_info.is_auth_realname == 0
                    ? '未实名'
                    : '-'}
                </ProDescriptions.Item>
                <ProDescriptions.Item span={12} label='经营信息'>
                  {record.inn_info.business_audit_status === 0 ? (
                    '未提交'
                  ) : (
                    <a
                      href={`http://admin.kuaidihelp.com/f/yz/innAuditDetailt?type=${record.inn_info.business_audit_status}&cm_id=${record.inn_info.cm_id}`}
                    >
                      {record.inn_info.business_audit_status === 1
                        ? '待审核'
                        : record.inn_info.business_audit_status === 2
                        ? '未通过'
                        : record.inn_info.business_audit_status === 3
                        ? '已通过'
                        : '-'}
                    </a>
                  )}
                </ProDescriptions.Item>
              </ProDescriptions>
            </>
          ) : null}
          {record.inn_stat ? (
            <>
              <Divider orientation='left'>驿站出入库统计</Divider>
              <DragTable>
                <ProTable
                  className='kb-pro-table'
                  dataSource={[record.inn_stat]}
                  columns={recordColumns}
                  size='middle'
                  search={false}
                  rowKey='id'
                  pagination={false}
                  options={false}
                  scroll={{ x: 1200 }}
                />
              </DragTable>
            </>
          ) : null}
          <Divider orientation='left'>驿站操作记录</Divider>
          {yzLogList.list.length > 0
            ? yzLogList.list.map((item: any) => {
                return (
                  <Row key={item.id}>
                    <Col span={6}>{item.create_time}</Col>
                    <Col span={18}>{item.content}</Col>
                  </Row>
                );
              })
            : null}
          {
            <Space style={{ display: 'flex', justifyContent: 'center', margin: 20 }}>
              {yzLogList.hasNextPage ? (
                <a onClick={() => getYzLog({ cm_id: record.inn_info.cm_id })}>更多</a>
              ) : (
                '加载完毕'
              )}
            </Space>
          }
          {showButton && (
            <Row justify='center' gutter={[40, 0]}>
              <Col style={{ paddingTop: 50 }}>
                <Popconfirm
                  title='确认通过？'
                  onConfirm={() => options({ id: record.inn_info.id, status: 1 })}
                >
                  <Button type='primary' key='agree'>
                    通过
                  </Button>
                </Popconfirm>
              </Col>
              <Col style={{ paddingTop: 50 }}>
                <Button danger key='refuse' onClick={() => setFormVisible(true)}>
                  驳回
                </Button>
              </Col>
              <Col style={{ paddingTop: 50 }}>
                <Popconfirm
                  title='确认扣钱不发？'
                  onConfirm={() => options({ id: record.inn_info.id, status: 3 })}
                >
                  <Button danger>扣钱不发</Button>
                </Popconfirm>
              </Col>
              <Col style={{ paddingTop: 50 }}>
                <Popconfirm
                  title='确认拉黑？'
                  onConfirm={() => options({ id: record.inn_info.id, status: 2 })}
                >
                  <Button danger>拉黑</Button>
                </Popconfirm>
              </Col>
            </Row>
          )}
        </Spin>

        <div style={{ height: 50 }}>
          <div
            style={{
              position: 'absolute',
              right: 0,
              bottom: 0,
              width: '100%',
              borderTop: '1px solid #e9e9e9',
              padding: '10px 16px',
              background: '#fff',
              textAlign: 'right',
            }}
          >
            <Button
              type='ghost'
              style={{ marginRight: 8 }}
              onClick={() =>
                handleDetail({
                  page_turn: 'next',
                  id: record.inn_info.id,
                })
              }
            >
              查看上一条
            </Button>
            <Button
              type='primary'
              onClick={() =>
                handleDetail({
                  page_turn: 'prev',
                  id: record.inn_info.id,
                })
              }
            >
              查看下一条
            </Button>
          </div>
        </div>
      </Drawer>
      <KbRefuseModal onCancel={handleHideMoal} visible={formVisible} onOk={handleSubmit} />
    </>
  );
};

export default CommonTable;
